package com.chain.qs.modules.biz.service;

import com.chain.qs.common.schedule.QuartzJobBean;
import com.chain.qs.common.service.CrudService;
import com.chain.qs.common.utils.TimeUtils;
import com.chain.qs.modules.biz.dao.HandoverDao;
import com.chain.qs.modules.biz.entity.Handover;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * 值班设置Service
 *
 */
@Service
//@Transactional(readOnly = true)
public class HandoverService extends CrudService<HandoverDao, Handover> {

    //定时任务组名标识，用于修改或更新任务
    private final static String JobGroupName = "handover";

    @Resource
    private HandoverTaskService handoverTaskService;

//    public Handover getCurHandover() {
//        //缓存中存在返回缓存中的内容,否则按时间从班次表里面拿数据
//        try {
//            Object obj = EhCacheUtils.get(EhCacheUtils.HANDOVER_CACHE, EhCacheUtils.HANDOVER_CUR_CACHE);
//            Handover handover = (obj != null)?(Handover)obj:null;
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//        }
//        return dao.getCurHandover();
//    }


    public Handover getHandover(){
        return dao.getHandover();
    }

    @Transactional(readOnly = false)
    public int saveAndDel(Handover handover){
        if(dao.getHandover().getIsActive() == 1){
            return -1; //提示用户，先关闭开启按钮，再操作。
        }
        if(dao.deleteOther() == 0){
            return -2;
        }
        save(handover);
        return 1;
    }

    @Transactional(readOnly = false)
    public int switchTo(Handover handover){
        if(handover.getIsActive() == 0){
            refreshDel();
        }else if(handover.getIsActive() == 1){
            refreshInit();
        }
        return dao.switchTo(handover);
    }

    private ArrayList<QuartzJobBean> parseToJobBeanList(Handover handover) {
        ArrayList<QuartzJobBean> list = Lists.newArrayList();
        if(handover == null) return list;

        TimeUtils endTime = new TimeUtils(handover.getEtime1());
        TimeUtils bufferTime = new TimeUtils(0, handover.getBufferTime(), 0);
        endTime = endTime.addTime(bufferTime);
        StringBuffer sb = new StringBuffer();
        sb.append(endTime.get(TimeUtils.SECOND) + " ");
        sb.append(endTime.get(TimeUtils.MINUTE) + " ");
        sb.append(endTime.get(TimeUtils.HOUR) + " ");
        sb.append("* * ? ");

        logger.debug("cronExpression is " + sb.toString());
        QuartzJobBean quartzJobBean = new QuartzJobBean();
//        quartzJobBean.setJobId("class1");
        quartzJobBean.setCronExpression(sb.toString());
        quartzJobBean.setDescription(handover.getName1());
        quartzJobBean.setJobGroup(JobGroupName);
        quartzJobBean.setJobName(handover.getName1());
        quartzJobBean.setJobStatus(2);
        list.add(0,quartzJobBean);

        if(handover.getEtime2() != null){
            endTime = new TimeUtils(handover.getEtime2());
            endTime = endTime.addTime(bufferTime);
            sb = new StringBuffer();
            sb.append(endTime.get(TimeUtils.SECOND) + " ");
            sb.append(endTime.get(TimeUtils.MINUTE) + " ");
            sb.append(endTime.get(TimeUtils.HOUR) + " ");
            sb.append("* * ? ");
            logger.debug("cronExpression is " + sb.toString());
            quartzJobBean = new QuartzJobBean();
//            quartzJobBean.setJobId("class2");
            quartzJobBean.setCronExpression(sb.toString());
            quartzJobBean.setDescription(handover.getName2());
            quartzJobBean.setJobGroup(JobGroupName);
            quartzJobBean.setJobName(handover.getName2());
            quartzJobBean.setJobStatus(2);
            list.add(0,quartzJobBean);
        }
        if(handover.getEtime3() != null){
            endTime = new TimeUtils(handover.getEtime3());
            endTime = endTime.addTime(bufferTime);
            sb = new StringBuffer();
            sb.append(endTime.get(TimeUtils.SECOND) + " ");
            sb.append(endTime.get(TimeUtils.MINUTE) + " ");
            sb.append(endTime.get(TimeUtils.HOUR) + " ");
            sb.append("* * ? ");
            logger.debug("cronExpression is " + sb.toString());
            quartzJobBean = new QuartzJobBean();
//            quartzJobBean.setJobId("class3");
            quartzJobBean.setCronExpression(sb.toString());
            quartzJobBean.setDescription(handover.getName3());
            quartzJobBean.setJobGroup(JobGroupName);
            quartzJobBean.setJobName(handover.getName3());
            quartzJobBean.setJobStatus(2);
            list.add(0,quartzJobBean);
        }
        return list;
    }
    public int getHandoverState(){
        return dao.getHandoverState();
    }

    public ArrayList<QuartzJobBean> getQuartzJobBeanList4ActivedHandover(){
        return parseToJobBeanList(dao.getAciveHandover());
    }

    public ArrayList<QuartzJobBean> getQuartzJobBeanList4NonDelHandover(){
        return parseToJobBeanList(dao.getHandover());
    }


    // 删除所有任务
    @Transactional(readOnly = false)
    private void refreshDel(){
        try {
            ArrayList<QuartzJobBean> handoverListPre = getQuartzJobBeanList4ActivedHandover();
            for (QuartzJobBean cur : handoverListPre) {
                handoverTaskService.delJob(cur);
            }
        } catch (Exception e) {
            System.out.println("删除后刷新失败");
        }
    }
    //重新初始化任务
    private void refreshInit(){
        try {
            refreshDel();
            ArrayList<QuartzJobBean> handoverListPre = getQuartzJobBeanList4NonDelHandover();
            for (QuartzJobBean cur : handoverListPre) {
                handoverTaskService.initJob(cur);
            }
        } catch (Exception e) {
            System.out.println("重新初始化失败");
        }
    }
}
